package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.util.StringUtil;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.constants.CacheConstants;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 *
 * @author zjf
 * @date 2025-06-09
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }


    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }


    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        // 请求参数
        ListProductsRequest request = new ListProductsRequest();
        // 每页显示记录数
        request.setLimit(10);
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-查询产品 同步失败");
        }

        // 获取产品列表
        List<ProductSummary> products = response.getProducts();

        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(products));
    }


    /**
     * 查询所有产品
     *
     * @return
     */

    @Override
    public List<ProductVo> allProduct() {
        //从redis中查询数据
        String json = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        //如果数据为空，则返回一个空集合
        if (StringUtil.isEmpty(json)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(json, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     * @return
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //判断设备是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        if (count(queryWrapper) > 0) {
            throw new BaseException("设备名称重复");
        }
        //判断设备标识码是否重复
        LambdaQueryWrapper<Device> queryWrapperNodeId = new LambdaQueryWrapper<>();
        queryWrapperNodeId.eq(Device::getNodeId, deviceDto.getNodeId());
        if (count(queryWrapperNodeId) > 0) {
            throw new BaseException("设备标识码重复");
        }
        //判断同一个位置是否绑定了同一类产品
        LambdaQueryWrapper<Device> condition = new LambdaQueryWrapper<>();
        condition.eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType());
        if (count(condition) > 0) {
            throw new BaseException("该老人或者物理位置已绑定该产品");
        }

        //iot新增设备
        //添加：添加产品id，添加设备名称，添加节点id
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());
        request.withBody(body);

        AuthInfo authInfobody = new AuthInfo();
        //密钥
        String secret = UUID.randomUUID().toString().replace("-", "");
        authInfobody.withSecret(secret);
        body.setAuthInfo(authInfobody);
        AddDeviceResponse response;

        try {
            //在iot平台上注册一个设备
            response = client.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口-注册设备 同步失败");
        }

        //设备数据保存到数据库中
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //设备id，密钥
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        //在数据库中新增设备
        try {
            save(device);
        } catch (Exception e) {
            throw new BaseException("数据库-新增设备 同步失败");
        }

    }

    /**
     * 获取设备详细信息
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询数据库
        Device device = getOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }
        //调用用华为云
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口-查询设备详情 调用失败");
        }

        //合并数据
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        //补充数据
        deviceDetailVo.setIotId(response.getDeviceId());
        //将时间设置为东八区时间
        String activeTime = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTime)) {
            LocalDateTime activeTime2 = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime2.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDate();
            deviceDetailVo.setActiveTime(activeTime2);
        }
        return deviceDetailVo;
    }

    /**
     * 查询设备上报数据
     *
     * @param iotId
     * @return
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-查询设备数据 同步失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollectionUtil.isEmpty(shadow)) {
            List<Object> objects = Collections.emptyList();
            return AjaxResult.success(objects);
        }
        //获取key vlue
        List<Map<String, Object>> list = new ArrayList<>();
        Object properties = shadow.get(0).getReported().getProperties();
        JSONObject json = JSONUtil.parseObj(properties);
        //获取时间
        String eventTime = shadow.get(0).getReported().getEventTime();

        LocalDateTime time = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime1 = time.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        json.forEach((k, v) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", k);
            map.put("value", v);
            map.put("eventTime", eventTime1);
            list.add(map);
        });
        return AjaxResult.success(list);
    }



    /**
     * 修改设备
     *
     * @param deviceDto 设备
     * @return 结果
     */
    @Override
    public void updateDevice(DeviceDto deviceDto) {
        //iot修改设备信息
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.getIotId());
        UpdateDevice body = new UpdateDevice();
        AuthInfoWithoutSecret authInfobody = new AuthInfoWithoutSecret();
        authInfobody.withSecureAccess(true);
        body.withDeviceName(deviceDto.getDeviceName());
        request.withBody(body);
        UpdateDeviceResponse response;
        try {
            response = client.updateDevice(request);
        } catch (Exception e) {
            throw new BaseException("巴拉巴拉异常");
        }
        //数据库修改设备信息
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        try {
            updateById(device);
        } catch (Exception e) {
            throw new BaseException("数据库异常,更新设备，更新失败");
        }

    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public void deleteDeviceById(String id) {
        //物联网删除
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(id);
        DeleteDeviceResponse response;
        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("删除设备时异常");
        }
        //数据库删除
        try {
            // 使用 LambdaQueryWrapper 指定按 iot_id 删除
            LambdaQueryWrapper<Device> deviceLambdaQueryWrapper = new LambdaQueryWrapper<Device>();
            boolean isRemoved = remove(deviceLambdaQueryWrapper.eq(Device::getIotId, id)  // 用 iot_id 匹配传入的 id
            );
            if (!isRemoved) {
                throw new BaseException("设备不存在或删除失败");
            }
        } catch (Exception e) {
            throw new BaseException("数据库删除设备时异常: " + e.getMessage());
        }
    }
    /**
     * 查询产品详情
     *
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        //参数校验
        if (StringUtils.isEmpty(productKey)) {
            throw new BaseException("产品Key不能为空");
        }

        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response;
        try {
            response = client.showProduct(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口-查询产品详情 同步失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollectionUtil.isNotEmpty(serviceCapabilities)) {
            return AjaxResult.success(serviceCapabilities);
        }
        return AjaxResult.success(serviceCapabilities) ;
    }
}

